package cc.zoyn.momentimageclubclient.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

import java.lang.reflect.Method;

/**
 * 网络工具类
 *
 * @author Zoyn
 * @since 2017-10-12
 */
public class NetworkUtils {

    private static Method getMobileDataEnabledMethod;

    /**
     * 获取网络信息
     *
     * @return {@link NetworkInfo}
     */
    private static NetworkInfo getActiveNetworkInfo() {
        return ((ConnectivityManager) BaseUtils.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    }

    /**
     * 判断是否拥有网络连接
     *
     * @return true: 是/false: 否
     */
    public static boolean hasWebConnected() {
        NetworkInfo info = getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

    /**
     * 判断wifi是否打开
     *
     * @return true: 是/false: 否
     */
    public static boolean isWifiEnabled() {
        WifiManager wifiManager = (WifiManager) BaseUtils.getApplication().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }

    /**
     * 判断移动数据是否打开
     *
     * @return true: 是/false: 否
     */
    public static boolean isDataEnabled() {
        try {
            TelephonyManager tm = (TelephonyManager) BaseUtils.getApplication().getSystemService(Context.TELEPHONY_SERVICE);
            if (getMobileDataEnabledMethod == null) {
                getMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("getDataEnabled");
            }
            return (boolean) getMobileDataEnabledMethod.invoke(tm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
